package logic

import (
	"context"
	"ginmt/pkg"
	"github.com/gin-gonic/gin"
	"github.com/sonhineboy/meituanMediaSdk/apis"
	"io"
	"log"
)

type MtService interface {
	GetValueByCity(context.Context, string) (string, error)
}

type ProductLogic struct {
	AppCtx    *pkg.AppCtx
	ctx       *gin.Context
	MtService MtService
}

func NewProductLogic(appCtx *pkg.AppCtx, ctx *gin.Context, mtService MtService) *ProductLogic {
	return &ProductLogic{
		AppCtx:    appCtx,
		ctx:       ctx,
		MtService: mtService,
	}
}

func (p *ProductLogic) GetProducts(reqBody *apis.RequestBody) ([]byte, error) {

	if reqBody.CityId != "" {
		city, err := p.MtService.GetValueByCity(p.ctx, reqBody.CityId)
		if err != nil {
			return nil, err
		}
		reqBody.CityId = city
	}

	queryProduct := apis.NewQueryCoupon(reqBody)

	log.Print(string(queryProduct.BuildBody()))
	headers := apis.NewHeaders(pkg.GetAppKey(), pkg.GetAppSecret(), queryProduct.BuildBody())
	exec, err := p.AppCtx.MtClient.Exec(queryProduct, headers)
	if err != nil {
		return nil, err
	}
	all, err := io.ReadAll(exec.Body)
	if err != nil {
		return nil, err
	}
	return all, nil
}
func (p *ProductLogic) GetLink(reqBody *apis.RequestBody) ([]byte, error) {
	reqBody.LinkTypeList = []int{1, 2, 3, 4, 5, 6}
	link := apis.NewReferralLink(reqBody)
	headers := apis.NewHeaders(pkg.GetAppKey(), pkg.GetAppSecret(), link.BuildBody())
	exec, err := p.AppCtx.MtClient.Exec(link, headers)
	if err != nil {
		return nil, err
	}
	all, err := io.ReadAll(exec.Body)
	if err != nil {
		return nil, err
	}
	return all, nil
}
